import os
import subprocess

import mimetypes
from damn.transcoder import TranscoderFailedException, BaseTranscoder

from damn.util import ExecutableDependencies

def GetNConvertPath():
  import platform
  from django.conf import settings
  if os.name == 'nt':
    bin = 'nconvert.exe'
  elif platform.architecture()[0] == '64bit':
    bin = 'nconvert64'
  else:
    bin = 'nconvert'
  path = getattr(settings, "NCONVERT", os.path.abspath(os.path.join(os.path.dirname(__file__), bin)))
  return path if os.path.exists(path) else False

ExecutableDependencies([GetNConvertPath()])

def RunNConvertURI(anURIin, anURIout, format, size=[None,None]):
  b = GetNConvertPath()
  if not b:
    print("E: RunNConvertURI failed! nconvert binary not found")
    return "", ""
  ext = mimetypes.guess_extension(format)
  if not ext:
    print("E: RunNConvertURI failed! unsupported format", format)
    return "", ""
  ext = ext.replace('.', '')
  if size == [None,None]:
    args = [b, '-out', ext,  '-overwrite', '-ratio', '-o', anURIout, anURIin]
  else:
    args = [b, '-out', ext,  '-overwrite', '-ratio', '-resize', str(size[0]), str(size[1]), '-o', anURIout, anURIin]
  p = None
  try:
    p = subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    s, t = p.communicate()
  except OSError:
    print("E: RunNConvertURI failed!", s, t)
  if p and p.returncode != 0:
    print("E: RunNConvertURI failed with error code %d! "%(p.returncode), t)
  return s, t 


class NConvertTranscoder(BaseTranscoder):
  transcoder = True if GetNConvertPath() else False
  convert_map = {"image/jpeg" : ["image/x-dds",], 
                 "image/png" : ["image/x-dds",], 
                 "image/x-photoshop" : ["image/jpeg", "image/png", "image/dds"], 
                 "image/x-dds" : ["image/png",]}
  _options = [('sizex', int, None), ('sizey', int, None),]
  options_map = {"image/jpeg" : _options, 
                 "image/png" : _options, 
                 "image/x-photoshop" : _options,
                 "image/x-dds" : _options,}

  def transcode(self, anAssetReference, dstFormat, **kwargs):  
    filePath = super(NConvertTranscoder, self).transcode(anAssetReference, dstFormat, kwargs)
    s, t = RunNConvertURI(anAssetReference.file.fileName, filePath, dstFormat, [kwargs['sizex'], kwargs['sizey']])
    return filePath


 
if __name__ == "__main__":
  class Asset:
    pass
  class File:
    def GetFullFileName(self):
      return "shield.png"
  ass = Asset()
  ass.id = '2a4e22dead049231e75d8a9c18cdcba95355da74'
  ass.format = "image/png"
  ass.file = File()
  n = NConvertTranscoder()
  print n.transcoder
  print n.transcode(ass, "image/x-dds", sizex=256, sizey=256)
